package com.kit.data.kitopeso.base;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

import androidx.viewbinding.ViewBinding;

import java.util.List;

/** @noinspection ALL*/
public abstract class BaseBindingAdapter<VB extends ViewBinding, T> extends BaseAdapter {
    protected final List<T> dataList;
    protected final LayoutInflater inflater;

    protected BaseBindingAdapter1.BtnItemClickListener onBtnItemClickListener;

    public BaseBindingAdapter(Context context, List<T> dataList) {
        this.dataList = dataList;
        this.inflater = LayoutInflater.from(context);
    }

    @Override
    public int getCount() {
        return dataList.size();
    }

    @Override
    public T getItem(int position) {
        return dataList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder<VB> holder;
        if (convertView == null) {
            VB binding = initViewBinding(inflater, parent);
            holder = new ViewHolder<>(binding);
            convertView = binding.getRoot();
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder<VB>) convertView.getTag();
        }
        bindData(holder.binding, getItem(position), position);
        return convertView;
    }

    protected abstract VB initViewBinding(LayoutInflater inflater, ViewGroup parent);

    protected abstract void bindData(VB binding, T item, int position);


    private static class ViewHolder<VB> {
        final VB binding;

        ViewHolder(VB binding) {
            this.binding = binding;
        }
    }

    public void updateData(List<T> newData) {
        dataList.clear();
        dataList.addAll(newData);
        notifyDataSetChanged();
    }

    public void setOnBtnItemClickListener(BaseBindingAdapter1.BtnItemClickListener onBtnItemClickListener) {
        this.onBtnItemClickListener = onBtnItemClickListener;
    }

    public void updateAllData() {
        notifyDataSetChanged();
    }

    public interface BtnItemClickListener {
        void onItecClick(int position);
    }

}